jQuery.fn.extend({ 
	
	dataTableCustom: function(urlApplication, edit, remove) {
		var tag = this;
		if(tag.length > 0){ addHeaderEditAndDelete(tag[0].localName + ' thead tr th', edit[0], remove[0]); }
		$(this).dataTable({
	        "bInfo": false,
	        "iDisplayLength": 5,
	        "aLengthMenu": [[5, 10, 25, 50, 100], [5, 10, 25, 50, 100]],
	        "sDom": '<"H"Tf>t<"F"ipl>',
	        "sPaginationType": "full_numbers",
	        "bPaginate": true,
	        "bServerSide": true,
	        "bLengthChange": true,
	        "sAjaxSource": contextPath + urlApplication,
	        "aoColumnDefs":  addColumnEditAndDelete(edit[1], remove[1]),
	        "oLanguage": {
	        	"oPaginate": {
	                "sFirst": "First page"
	              }
	        },
	        "aoSearchCols": [{ "sSearch": "^[0-9]", "bEscapeRegex": false }]
	    });
	},
	redrawDataTable: function(){
		this.fnDraw();
	}
});	

function addHeaderEditAndDelete(tag, headerEdit, headerDelete){		
	if(headerEdit != null){ 
		$(tag).last().after('<th>' + headerEdit + '</th>');
	}
	if(headerDelete != null){ 
		$(tag).last().after('<th>' + headerDelete + '</th>');
	}
}

function addColumnEditAndDelete(urlEdit, urlDelete){		
	if(urlEdit != null && urlDelete != null){ return [addEdit(urlEdit, -2), addRemove(urlDelete, -1)];}
	if(urlEdit != null){ return [addEdit(urlEdit, -1)];}
	if(urlDelete != null){ return [addRemove(urlDelete, -1)];}
}	

function addEdit(urlEdit, column){
	return {"sName": "edit",
	        "bSearchable": false,
	        "bSortable": false,
	        "sClass": "botao",
	        "fnRender": function (oObj) {
	     	   return '<a id="update" href="' + contextPath + urlEdit + oObj.aData[0] + '">' + 
	     	   		     '<img src="' + contextPath + '/resources/images/edit.png" alt="alterar" />' + 
	     	   		  '</a>';
	        },
	        "aTargets": [column]
	     };	
}

function addRemove(urlDelete, column){
	return {"sName": "delete",
	        "bSearchable": false,
	        "bSortable": false,
	        "sClass": "botao",
	        "fnRender": function (oObj) {
	      	   return '<a id="remove" href="' + contextPath + urlDelete + oObj.aData[0] + '">' + 
	      	   		     '<img src="' + contextPath + '/resources/images/icon-delete.gif" alt="remover" />' + 
	      	   		  '</a>';
	        },
	        "aTargets": [column]
		};
}
